package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.component.SmsComponent;
import org.example.config.SmsConfig;
import org.example.constant.RedisKey;
import org.example.enums.BizCodeEnum;
import org.example.enums.SendCodeEnum;
import org.example.service.NotifyService;
import org.example.util.CheckUtil;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 谢超
 * @date: 2023/07/19 21:59
 **/
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
    /**
     * 10分钟有效
     */
    private static final int CODE_EXPIRED = 60 * 1000 * 10;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private SmsComponent smsComponent;

    @Resource
    private SmsConfig smsConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Async("threadPoolTaskExecutor")
    public void testSend() {
        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // http://old.xdclass.net 网站已经失效，导致访问错误
//        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://old.xdclass.net", String.class);
//        String body = forEntity.getBody();
//        log.info(body);
    }

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);

        // 如果不为空，再判断是否是60秒内重复发送
        if (StringUtils.isNoneBlank(cacheValue)) {
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            // 当前时间戳 - 验证码发送的时间戳，如果小于60s，则不给重复发送
            long gap = CommonUtil.getCurrentTimestamp() - ttl;
            if (gap < (1000 * 60)) {
                log.info("重复发送验证码:{}", gap);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        String code = CommonUtil.getRandomCode(6);
        // 生成拼接好的验证码
        String value = code + "_" + CommonUtil.getCurrentTimestamp();
        stringRedisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRED, TimeUnit.MILLISECONDS);

        if (CheckUtil.isEmail(to)) {
            // 发送邮箱验证码 TODO

        } else if (CheckUtil.isPhone(to)) {
            // 发送手机验证码
            smsComponent.send(to, smsConfig.getTemplateId(), code);
        }
        return JsonData.buildSuccess();
    }

    /**
     * 验证码校验逻辑
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        log.info("cacheKey:{}", cacheKey);
        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);

        if (cacheValue != null && StringUtils.isNoneBlank(cacheKey)) {
            String cacheCode = cacheValue.split("_")[0];
            // 如果验证码校验正确，则需要删除redis中保存发送的验证码，不需要让验证码在redis中了
            if (cacheCode.equalsIgnoreCase(code)) {
                // 删除验证码
                stringRedisTemplate.delete(code);
                return true;
            }
        }
        return false;
    }
}
